﻿//--------------------------------------------------------------------------------------------------------------
// <copyright file="CSPBaseWUC.cs" company="Microsoft Corporation" author="David Martos" date="01/01/2008">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//--------------------------------------------------------------------------------------------------------------


using System;
using System.Collections;
using System.Collections.Specialized;
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
using Microsoft.Security.Application;

using CKS.FormsBasedAuthentication.HIP;


namespace CSP.WebParts.UserControls
{

    /// <summary>
    /// Manages all the common functions of the webparts
    /// </summary>       
    public class CSPBaseWUC : System.Web.UI.UserControl
    {

        #region Members       
        public BaseWebPart WrapperWebPart { get; set; }

            protected CSP.Core.ResourceFile resourceFile;

            protected enum CharMix { upper, lower, mix }

            protected string[] _randCharacters = { "A","B","C","D","E","F","G","H","J","K","L","M","N","P","Q","R","S","T","U","V","W","X","Y","Z",
                    "2","3","4","5","6","7","8","9",
                    "a","b","c","d","e","f","g","h","j","k","m","n","p","q","r","s","t","u","v","w","x","y","z"};
         
            protected Panel pnlHip;
            protected ImageHipChallenge imgHip;
            protected HipValidator vldHip;
            protected TextBox txtHip;
            protected Label lblHipPicture;
            protected Label lblHipCharacters;
            protected Label lblHipInstructions;
            protected Label lblHipPictureDescription;
            protected LinkButton lnkHip;

            private StringBuilder errorLog;
        #endregion


        #region PageEvents
            /// <summary>
            /// Fired on page init
            /// </summary>  
            protected override void OnInit(EventArgs e)
            {
                try{
                    resourceFile = new CSP.Core.ResourceFile();
                }              
                catch (CSP.Core.CSPException cspex)
                {
                    throw cspex;
                }
                catch (Exception ex)
                {
                    this.LogMessage(this.LoadResource(WebPartConstants.CSPGenericErrorMessage), this.GetType().Name, ex);
                    throw ex;
                }
            }
        #endregion

        #region Methods
        /// <summary>
        /// Creates a new entry into the standard WSS log file with the given information
        /// </summary>
        /// <param name="errorMessageKey">Resource file key which defines the error message</param>
        /// <param name="errorCategoryKey">Resource file key which defines the error category</param>
        protected void LogMessage(string errorMessageKey, string errorCategoryKey, Exception ex)
        {
            string applicationName = resourceFile.LoadResource(WebPartConstants.CSPErrorApplicationName);
            string errorMessage = resourceFile.LoadResource(errorMessageKey);
            string errorCategory = resourceFile.LoadResource(errorCategoryKey);

            CSP.LoggingEngine.Utils.LogError(errorMessage, errorCategory, applicationName, ex);
        }

        /// <summary>
        /// Creates a new entry into the standard WSS log file with the given information
        /// </summary>
        /// <param name="errorMessageKey">Resource file key which defines the error message</param>
        /// <param name="errorCategoryKey">Resource file key which defines the error category</param>
        protected void LogMessage(string errorMessageKey, string errorCategoryKey)
        {
            string applicationName = resourceFile.LoadResource(WebPartConstants.CSPErrorApplicationName);
            string errorMessage = resourceFile.LoadResource(errorMessageKey);
            string errorCategory = resourceFile.LoadResource(errorCategoryKey);

            CSP.LoggingEngine.Utils.LogError(errorMessage, errorCategory, applicationName);
        }

       

        /// <summary>
        /// Find all the Labels and Buttons in the control and changes it Text property.
        /// </summary>
        /// <param name="parent">Control where the Buttons and Labels are in</param>           
        protected void LoadLabels(Control parent) {

            foreach (Control c in parent.Controls)
            {
                if (c.GetType().ToString().Contains("Label"))
                {
                    Label l;
                    l = ((Label)c);
                    l.Text = AntiXss.HtmlEncode(this.LoadResource(c.ID));
                }
                else {
                    if (c.GetType().ToString().Contains("Button")) {
                        Button b;
                        b = ((Button)c);
                        b.Text = this.LoadResource(c.ID);
                    }
                }                    
            }
        }

        /// <summary>
        /// Translates a literal into the application language
        /// </summary>
        /// <param name="id">Literal to be translated</param>
        /// <returns>Translation</returns>
        public string LoadResource(string id)
        {
            string translatedResource;

            try
            {
                translatedResource = resourceFile.LoadResource(id);
            }
            catch
            {
                translatedResource = string.Format(LoadResource("ERROR_Resource_file"), id);
            }

            return translatedResource;
        }

        /// <summary>
        /// Adds the HIP controls to the Web Control
        /// </summary>
        protected void AddHipControls()
        {
            TableRow tr;
            TableCell td;
            TableCell td2;
            Table table = new Table();

            lblHipPicture = new Label();
            //lblHipPicture.Text = HipPictureLabelText;
            StringCollection scWords = new StringCollection();
            string randString = GenerateRandomString(6, CharMix.mix);
            scWords.Add(randString);
            imgHip = new ImageHipChallenge();
            imgHip.ID = "imgHip";
            imgHip.Width = Unit.Pixel(210);
            imgHip.Height = Unit.Pixel(70);
            imgHip.Words = scWords;

            table.CellPadding = 0;
            table.CellSpacing = 0;

            tr = new TableRow();
            td = new TableCell();
            td2 = new TableCell();
            td.HorizontalAlign = HorizontalAlign.Right;
            td2.HorizontalAlign = HorizontalAlign.Left;
            td.Controls.Add(lblHipPicture);
            td2.Controls.Add(imgHip);
            tr.Cells.Add(td);
            tr.Cells.Add(td2);
            table.Rows.Add(tr);

            lblHipInstructions = new Label();
            lblHipInstructions.Text = this.LoadResource("HipInstructions");

            tr = new TableRow();
            td = new TableCell();
            td2 = new TableCell();
            td2.HorizontalAlign = HorizontalAlign.Left;
            td2.Controls.Add(lblHipInstructions);
            tr.Cells.Add(td);
            tr.Cells.Add(td2);
            table.Rows.Add(tr);

            txtHip = new TextBox();
            txtHip.ID = "txtHip";
            txtHip.MaxLength = 20;
            lblHipCharacters = new Label();
            vldHip = new HipValidator();
            vldHip.ID = "vldHip";
            vldHip.Display = ValidatorDisplay.Dynamic;
            vldHip.ControlToValidate = txtHip.ID;
            vldHip.ValidationGroup = this.ID;
            vldHip.HipChallenge = imgHip.ID;
            vldHip.EnableClientScript = true;
            vldHip.Text = this.LoadResource("HipErrorMessage");
            vldHip.ErrorMessage = this.LoadResource("HipErrorMessage");

            tr = new TableRow();
            td = new TableCell();
            td2 = new TableCell();
            td.HorizontalAlign = HorizontalAlign.Right;
            td2.HorizontalAlign = HorizontalAlign.Left;
            td.Controls.Add(lblHipCharacters);
            td2.Controls.Add(txtHip);
            td2.Controls.Add(vldHip);
            tr.Cells.Add(td);
            tr.Cells.Add(td2);
            table.Rows.Add(tr);

            lnkHip = new LinkButton();
            lnkHip.Click += new EventHandler(lnkHip_Click);
            lnkHip.Text = this.LoadResource("HipReset");
            lnkHip.CausesValidation = false;

            tr = new TableRow();
            td = new TableCell();
            td2 = new TableCell();
            td2.HorizontalAlign = HorizontalAlign.Left;
            td2.Controls.Add(lnkHip);
            tr.Cells.Add(td);
            tr.Cells.Add(td2);
            table.Rows.Add(tr);

            this.pnlHip.Controls.Add(table);
        }

        /// <summary>
        /// Returns a combination of letters and numbers for the HIP control
        /// </summary>
        /// <param name="id">Literal to be translated</param>
        /// <returns>Generated String</returns>
        protected string GenerateRandomString(int NumAlphs, CharMix Mix)
        {
            Random rGen = new Random();

            int iMix = (int)Mix;

            int p = 0;
            string sPass = "";
            int iCharMax = 32;
            if (iMix > 0) iCharMax = 55;
            for (int x = 0; x < NumAlphs; x++)
            {
                p = rGen.Next(0, iCharMax);
                sPass += _randCharacters[p];
            }
            if (iMix < 1)
            {
                sPass = sPass.ToUpper();
            }
            else if (iMix < 2)
            {
                sPass = sPass.ToLower();
            }
            return sPass;
        }

        /// <summary>
        /// Fired on Log Exception
        /// </summary>  
        protected void LogException(Exception e)
        {
            if (this.errorLog == null)
                this.errorLog = new StringBuilder();

            errorLog.AppendLine(e.Message + "<br/>");
        }
        #endregion


        #region ControlEvents    
        /// <summary>
        /// Fired on Hip link click
        /// </summary>  
        void lnkHip_Click(object sender, EventArgs e)
        {
            //Nothing to do, the image will reset automatically
        }


        /// <summary>
        /// Fired on gridview paging
        /// </summary>  
        protected void GridViewPageChangedCommand(GridView gv, GridViewPageEventArgs e)
        {
            try
            {
                gv.PageIndex = e.NewPageIndex;
            }
            catch (Exception ex)
            {
                LogException(ex);
            }
        }

        /// <summary>
        /// Fired on gridview sorting
        /// </summary>  
        protected void GridViewSortCommand(GridView gv, GridViewSortEventArgs e)
        {

            try
            {
                gv.PageIndex = 0;
                string sortExpression = (string)ViewState["SortExp"];
                string sortDirection = (string)ViewState["SortDir"];

                if (sortExpression != e.SortExpression)
                {
                    sortExpression = e.SortExpression;
                    sortDirection = "asc";
                }
                else
                {
                    if (sortDirection == "asc")
                        sortDirection = "desc";
                    else
                        sortDirection = "asc";
                }

                ViewState["SortExp"] = sortExpression;
                ViewState["SortDir"] = sortDirection;
            }
            catch (Exception ex)
            {
                LogException(ex);
            }
        }
        #endregion
    }
}
